<template>
  <div id="attach" style="width: 100%; justify-content: center; display: flex">
    <div style="width: 100%">
      <div>
        <!-- <ht-upload
          ref="myUpload"
          multiple
          dbKey="Trd"
          busField="library"
          busType="1"
          ftpKey="ftp"
          v-model="fileList"
          :show-file-list="false"
        >
          <a-button slot="trigger" icon="upload">新增附件</a-button>
          <a-button style="margin-left: 10px; margin-bottom: 10px" icon="delete" @click="deleteAttach"> 删除 </a-button>
        </ht-upload> -->
        <hte-upload     dbKey="Trd"
          busField="library"
          busType="1"
          ftpKey="ftp"
          v-model="fileDataList"
          :show-file-list="false"
          :onSuccess="onSuccess"
          :uploadShow="false"
          ref="upload"
          > 
          
       
          <span slot="btn">
            <a-button   type="primary" @click="beforeUpload('minUploadBtn')">上传</a-button>
            <a-button style="margin-left: 10px; margin-bottom: 10px"  type="primary" @click="beforeUpload('largeUploadBtn')">大文件上传</a-button>
            <a-button style="margin-left: 10px; margin-bottom: 10px" icon="delete" @click="deleteAttach"> 删除 </a-button>
          </span>
          </hte-upload>
      </div>
      <div>
        <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                  <template slot="title">
                    附件上传原则：<br />                   
                    1、正文附件和文件属性“文件名称”保持一致。<br />
                    2、上传其它附件先选择一个正文附件再上传。
                  </template>
        <a-table
          :columns="columns"
          :data-source="fileList"
          rowKey="id"
          bordered
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="handleTableChange"
          :pagination="ipagination"
          defaultExpandAllRows
        >
          <span slot="fileName" slot-scope="text, record">
            <a icon="download" @click="handlePreview(record)">{{ text }}</a>
          </span>

        </a-table>
        </a-tooltip>
      </div>
    </div>
    <a-modal
      title="请选择添加的附件类型"
      :visible="nodeTypeSel.visible"
      @ok="nodeTypeSelOk"
      @cancel="nodeTypeSelCancel"
    >
      <ul class="info-list">
        <li style="margin-bottom: 20px">
          <img src="@/assets/dbcircle.png" alt="" />
          <span class="list-title">附件类型：</span>
          <a-select
            style="width: 200px"
            v-model="nodeTypeSel.value"
            placeholder="请选择"
            :options="nodeTypeSel.options"
          >
          </a-select>
        </li>
      </ul>
    </a-modal>
  </div>
</template>

<script>
import '@/config/upload.install.js';
import '@/config/hteupload.install.js';
import { formatSize } from '@/components/hteUpload/common/utils'
import { gnetAction } from '@/api/manage';
// import * as localStorage from '@/utils/localStorage';
// import * as RequestHost from '@/api/env';

const columns = [
  {
    title: '附件名称',
    dataIndex: 'fileName',
    key: 'fileName',
    scopedSlots: { customRender: 'fileName' }
  },
  {
    title: '文件大小',
    dataIndex: 'size',
    key: 'size',
    customRender:function (text) {
          return formatSize(text)
    },
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    key: 'uploadTime'
  }
];
export default {
  components: {},
  props: {
    hteFile: {
      type: Object,
      default: () => {}
    },
    parentId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      fileType:'',
      nodeTypeSel: {
        visible: false,
        value: '',
        options: [
          { label: '正文', value: '0' },
          { label: '其它附件', value: '1' },
        ],
      },
      columns,
      fileList: [],
      fileDataList: [],
      busKey: '',
      selectedRowKeys: [],
      selectionRows:[],
      url: {
        list: '/lib/attach/list',
        updateFilePath: '/lib/attach/updateFilePath',
      },
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条';
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    };
  },
  created() {
    this.busKey = this.hteFile.id;
  },
  methods: {
    onSuccess(res,attach){
     attach.attachId = attach.id
     if (this.nodeTypeSel.value == '0') {
      attach.contentFlag = 1
      attach.parentId = 0
      this.fileList.push(attach)
    }else{
      attach.contentFlag = 0
      let parentRow = this.selectionRows[0]
      attach.parentId = parentRow.id
      var children = !parentRow.children?[]:parentRow.children
      children.push(attach)
      parentRow.children = children
      var index = this.fileList.findIndex(item=>{return item.id == parentRow.id})
      this.$set(this.fileList,index,parentRow)
    }
     
    },
    beforeUpload(fileType){
      const vm = this
      this.fileType = fileType
      this.nodeTypeSel.visible = true
    },
    nodeTypeSelOk() {
      this.nodeTypeSel.visible = false
      debugger
      if (this.nodeTypeSel.value == '0') {
      }
      if (this.nodeTypeSel.value == '1') {
        if (this.selectionRows.length !== 1) {
          this.$message.warning('请选择一个正文附件进行添加其它附件')
          return
        }
        if ( this.selectionRows[0].contentFlag != '1') {
          this.$message.warning('只能对正文附件添加其它附件')
          return
        }
      }
      this.$refs.upload.$refs[this.fileType].$el.click()
    },
    clearSelect(){
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    nodeTypeSelCancel() {
      this.nodeTypeSel.visible = false
      this.nodeTypeSel.value = ''
    },
    /**
     * 表结构切换页码
     */
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination;
      this.ipagination.pageNo = this.ipagination.current;
      this.listAttachment(this.fileId, this.version);
    },


    onSelectChange(selectedRowKeys,selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
       this.selectionRows = selectionRows;
    },
    deleteAttach() {
       const that = this;
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请选中要删除的附件');
        return false;
      }
      function callBack() {
          that.selectionRows.forEach(item => { 
            if(item.parentId == 0){
                const idx = that.fileList.findIndex((value)=>value.id==item.id)
            
              if(idx != -1){that.fileList.splice(idx,1);}
            }else{
              let parentData = that.fileList.filter((value) => {
                return value.id === item.parentId
              })
              if(parentData && parentData.length > 0){
                  let index = 0
                  parentData[0].children.forEach((value) => {
                    if (value.id === item.id) {
                      parentData[0].children.splice(index, 1)
                    }
                   index++
                  })
              }
            
            }
            
            
          });
          
          that.clearSelect()
        }
         let deleteKeys = that.selectedRowKeys 
      let deleteRows = that.selectionRows 
     
      that.$refs.upload.delete(deleteKeys,deleteRows,callBack)
      return
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中附件?',
        onOk: function() {
          that.selectedRowKeys.forEach(key => { 
            const idx = that.fileList.findIndex((value)=>value.id==key)
            
            if(idx != -1){that.fileList.splice(idx,1);}
            
          });
          that.selectedRowKeys = []
          // getAction(that.url.delete, { fileId: that.hteFile.id, ids: ids }).then(res => {
          //   if (res.success) {
          //     that.$message.error('删除成功');
          //     if (res.result.draftVersion == that.hteFile.draftVersion) {
          //       that.listAttachment(that.hteFile.id, that.hteFile.draftVersion);
          //     } else {
          //       that.$emit('reload', res.result);
          //     }
          //   } else {
          //     that.$message.error('删除失败');
          //   }
          // });
        }
      });
    },

    handlePreview(row) {
      // const token = '';//localStorage.getStore('Authorization');
      // const url = RequestHost.hxUrl + '/lib/attach/preview?Authorization=' + token + '&id=' + row.id + '&ftpKey=ftp';
      // window.open('/risk/pdf/web/viewer.html?file=' + encodeURIComponent(url));
       let that = this
      let record = row
      that.$refs.upload.handlePreview(record)
    },

  },
};
</script>

<style lang="less">

.el-upload__input {
  display: none;
}
.el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
.info-list {
  display: flex;
  flex-wrap: wrap;
  border-bottom: 1px dashed #ebebeb;
  > li {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;
    > img {
      margin-right: 5px;
    }
    .list-title {
      width: 150px;
      font-weight: 900;
    }
  }
}

.new-tooltip {
  min-width: 410px !important;
}
</style>
